package com.liaoban.app.ui.login;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;

import com.jakewharton.rxbinding2.view.RxView;
import com.jakewharton.rxbinding2.widget.RxTextView;
import com.liaoban.app.R;
import com.liaoban.app.api.type.request.RegisterRequest;
import com.liaoban.app.api.type.request.SmsRequest;
import com.liaoban.app.biz.CommonBiz;
import com.liaoban.app.constants.ExtraParam;
import com.liaoban.app.helper.ToastHelper;
import com.liaoban.app.ui.base.BaseToolbarActivity;
import com.liaoban.app.widget.MyTextWatcher;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.picker.SinglePicker;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by ybc on 2018/7/6 0006.
 * 注册第二步
 */
public class RegisterTwoActivity extends BaseToolbarActivity {

    @BindView(R.id.et_ver_code)
    EditText etVerCode;
    @BindView(R.id.tv_ver_code)
    TextView tvVerCode;
    @BindView(R.id.et_yaoqing_code)
    EditText etYaoQingCode;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.tv_submit)
    TextView tvSubmit;

    private String mPhone;
    private String mPwd;
    //最大倒计时长
    private static final long MAX_COUNT_TIME = 90;
    private Observable<Long> mObservableCountTime;
    private Consumer<Long> mConsumerCountTime;
    //用于主动取消订阅倒计时，或者退出当前页面。
    private Disposable mDisposable;
    private Disposable mDisposableFirst;

    public static Intent newIntent(Context context, String phone, String pwd) {
        Intent intent = new Intent(context, RegisterTwoActivity.class);
        intent.putExtra(ExtraParam.PHONE, phone);
        intent.putExtra(ExtraParam.PWD, pwd);
        return intent;
    }

    @Override
    protected String getNewTitle() {
        return "+86" + mPhone;
    }

    @Override
    protected int getLayoutResID() {
        return R.layout.activity_register_two;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        mPhone = getIntent().getStringExtra(ExtraParam.PHONE);
        mPwd = getIntent().getStringExtra(ExtraParam.PWD);
        initListener();
        initFirstCountDown();
    }

    private void initListener() {
        MyTextWatcher myTextWatcher = new MyTextWatcher(() -> {
            if (etVerCode.getText().toString().trim().length() > 0) {
                tvSubmit.setEnabled(true);
                tvSubmit.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                tvSubmit.setEnabled(false);
                tvSubmit.setBackgroundResource(R.drawable.shape_line);
            }
        });
        etVerCode.addTextChangedListener(myTextWatcher);
    }

    private void initFirstCountDown() {
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .take(MAX_COUNT_TIME)
                .map(aLong -> MAX_COUNT_TIME - (aLong + 1))
                .observeOn(AndroidSchedulers.mainThread())//ui线程中进行控件更新
                .doOnSubscribe(disposable -> {
                    //更新发送按钮的状态并初始化显现倒计时文字
                    RxView.enabled(tvVerCode).accept(false);
                    RxTextView.text(tvVerCode).accept(MAX_COUNT_TIME + " 秒");
                    tvVerCode.setBackgroundResource(R.drawable.shape_line);
                    //在实际操作中可以在此发送获取网络的请求,,续1s
                    SmsRequest smsRequest = new SmsRequest();
                    smsRequest.setUserTel(mPhone);
                    startTask(CommonBiz.getInstance().duanxin(smsRequest), smsBaseResponse -> ToastHelper.show(RegisterTwoActivity.this, smsBaseResponse.msg));
                }).subscribe(new Observer<Long>() {
            @Override
            public void onSubscribe(Disposable d) {
                mDisposableFirst = d;
            }

            @Override
            public void onNext(Long num) {
                try {
                    RxTextView.text(tvVerCode).accept(num + " 秒");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tvVerCode.setBackgroundResource(R.drawable.shape_line);
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {
                //回复原来初始状态
                try {
                    RxView.enabled(tvVerCode).accept(true);
                    RxTextView.text(tvVerCode).accept(getString(R.string.resend));
                } catch (Exception e) {
                    e.printStackTrace();
                }
                tvVerCode.setBackgroundResource(R.drawable.shape_yellow);
                countDown();
            }
        });

    }

    @OnClick(R.id.tv_submit)
    public void submit() {
        showRunningDialog();
        RegisterRequest registerRequest = new RegisterRequest();
        registerRequest.setUserTel(mPhone);
        registerRequest.setPassword(mPwd);
        registerRequest.setCode(etVerCode.getText().toString().trim());
        registerRequest.setYaoqing_code(etYaoQingCode.getText().toString().trim());
        registerRequest.setSex("男".equals(tvSex.getText().toString().trim()) ? "2" : "1");
        startTask(CommonBiz.getInstance().register(registerRequest), objectBaseResponse -> {
            ToastHelper.show(RegisterTwoActivity.this, objectBaseResponse.msg);
            if (objectBaseResponse.code == 1) {
                setResult(0);
                finish();
            }
        });
    }

    /**
     * 倒计时
     */
    private void countDown() {
        mObservableCountTime = RxView.clicks(tvVerCode)
                //防止重复点击
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribeOn(AndroidSchedulers.mainThread())
                .flatMap(o -> Observable.just(true))
                //将点击事件转换成倒计时事件
                .flatMap(o -> {
                    //更新发送按钮的状态并初始化显现倒计时文字
                    RxView.enabled(tvVerCode).accept(false);
                    RxTextView.text(tvVerCode).accept(MAX_COUNT_TIME + " 秒");
                    tvVerCode.setBackgroundResource(R.drawable.shape_line);
                    //在实际操作中可以在此发送获取网络的请求,,续1s
                    SmsRequest smsRequest = new SmsRequest();
                    smsRequest.setUserTel(mPhone);
                    startTask(CommonBiz.getInstance().duanxin(smsRequest), smsBaseResponse -> ToastHelper.show(RegisterTwoActivity.this, smsBaseResponse.msg));
                    return Observable.interval(1, TimeUnit.SECONDS, Schedulers.io())
                            .take(MAX_COUNT_TIME)
                            //将递增数字替换成递减的倒计时数字
                            .map(aLong -> MAX_COUNT_TIME - (aLong + 1));
                })
                //切换到 Android 的主线程。
                .observeOn(AndroidSchedulers.mainThread());

        mConsumerCountTime = aLong -> {
            //当倒计时为 0 时，还原 btn 按钮
            if (aLong == 0) {
                RxView.enabled(tvVerCode).accept(true);
                RxTextView.text(tvVerCode).accept(getString(R.string.resend));
                tvVerCode.setBackgroundResource(R.drawable.shape_yellow);
            } else {
                RxTextView.text(tvVerCode).accept(aLong + " 秒");
                tvVerCode.setBackgroundResource(R.drawable.shape_line);
            }
        };
        //订阅
        mDisposable = mObservableCountTime.subscribe(mConsumerCountTime);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mDisposable != null) {
            mDisposable.dispose();
        }
        if (mDisposableFirst != null) {
            mDisposableFirst.dispose();
        }
    }

    @OnClick(R.id.layout_sex)
    public void layoutSex() {
        SinglePicker<String> picker = new SinglePicker<>(this,
                new String[]{
                        "男", "女"
                });
        picker.setCanLoop(true);//不禁用循环
        picker.setTopBackgroundColor(getResources().getColor(R.color.white));
        picker.setTopHeight(50);
        picker.setTopLineColor(getResources().getColor(R.color.line));
        picker.setTopLineHeight(1);
        picker.setTitleText("请选择");
        picker.setTitleTextColor(getResources().getColor(R.color.text_black));
        picker.setTitleTextSize(15);
        picker.setCancelTextColor(getResources().getColor(R.color.text_black));
        picker.setCancelTextSize(13);
        picker.setSubmitTextColor(getResources().getColor(R.color.text_black));
        picker.setSubmitTextSize(13);
        picker.setSelectedTextColor(getResources().getColor(R.color.btn_yellow));
        picker.setUnSelectedTextColor(getResources().getColor(R.color.text_gray));
        LineConfig config = new LineConfig();
        config.setColor(getResources().getColor(R.color.btn_yellow));//线颜色
        config.setAlpha(140);//线透明度
        config.setRatio((float) (1.0 / 8.0));//线比率
        picker.setLineConfig(config);
        picker.setItemWidth(200);
        picker.setBackgroundColor(getResources().getColor(R.color.white));
        picker.setOnItemPickListener((index, item) -> {
            tvSex.setText(item);
        });
        picker.show();
    }

}
